package com.finance.task;

import com.finance.entity.AsyncRequest;
import com.finance.service.AsyncRequestService;
import com.finance.service.FinanceDataSyncService;
import com.finance.util.DataType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Slf4j
@Component
public class AsyncRequestTask {

    @Autowired
    private AsyncRequestService asyncRequestService;
    
    @Autowired
    private FinanceDataSyncService financeDataSyncService;
    
    /**
     * 每5分钟执行一次
     */
    @Scheduled(fixedRate = 300000)
    public void processAsyncRequests() {
        log.info("开始处理异步请求...");
        List<AsyncRequest> pendingRequests = asyncRequestService.getPendingRequests();
        
        for (AsyncRequest request : pendingRequests) {
            try {
                // 更新状态为处理中
                asyncRequestService.updateStatus(request.getId(), 1, null);
                
                // 重新调用API获取数据
                DataType dataType = DataType.fromCode(request.getDataType());
                if (dataType != null) {
                    LocalDate date = LocalDate.parse(request.getSearchDate(), DateTimeFormatter.ISO_DATE);
                    financeDataSyncService.syncDataByType(dataType, date, false);
                    // 更新状态为已完成
                    asyncRequestService.updateStatus(request.getId(), 2, null);
                } else {
                    throw new IllegalArgumentException("Invalid data type: " + request.getDataType());
                }
            } catch (Exception e) {
                log.error("处理异步请求失败: {}", e.getMessage());
                // 增加重试次数
                asyncRequestService.incrementRetryCount(request.getId());
                // 更新状态为失败
                asyncRequestService.updateStatus(request.getId(), 3, e.getMessage());
            }
        }
        log.info("异步请求处理完成，共处理 {} 个请求", pendingRequests.size());
    }
} 